package vn.com.atm;

import org.json.JSONException;
import org.json.JSONObject;

import vn.com.atm.database.UserFunctions;
import vn.com.atm.library.Alert;
import vn.com.atm.library.SimpleCrypto;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class UserActivity extends Activity {
	
	private TextView eUserName;
	private EditText ePassword, eEmail, eFullName;
	private Button btnCapnhat;
	UserFunctions userFunction; ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_userprofile);
		
		eUserName = (TextView) findViewById(R.id.eUserName);
		ePassword = (EditText) findViewById(R.id.ePassword);
		eEmail = (EditText) findViewById(R.id.eEmail);
		eFullName = (EditText) findViewById(R.id.eFullName);
		btnCapnhat = (Button) findViewById(R.id.btnCapnhat);
		final SimpleCrypto sp = new SimpleCrypto();
		SharedPreferences preference = getSharedPreferences(LoginActivity.USER_PROFILE, Activity.MODE_PRIVATE);
		
		String userName = preference.getString(LoginActivity.KEY_USERNAME, "Chua dang nhap");
		
		eUserName.setText(userName);
		
		userFunction = new UserFunctions();
		
		JSONObject json = userFunction.profileUser(userName);
		
		try {
			if (json.getString("SUCCESS") != null) {
				String email = json.getString("email");
				String fullname = json.getString("fullname");
				eEmail.setText(email);
				eFullName.setText(fullname);
				ePassword.setText("");
			}
		} catch (JSONException e) {
		}
		
		
		btnCapnhat.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				userFunction = new UserFunctions();
				String pEmail = eEmail.getText().toString();
				String pfullname = eFullName.getText().toString();
				String pPass = ePassword.getText().toString();
				String pUserName = eUserName.getText().toString();
			try {
				pPass = sp.encrypt("key", pPass);
				
				
			} catch (Exception e) {
			}
			
			JSONObject json = userFunction.updatePass(pUserName, pPass, pEmail, pfullname);
			Alert alert = new Alert();
			try {
				if(json.getString("status").equals("SUCCESS")== true)
				{
					alert.AlertError(UserActivity.this, "Thông báo", "Cập nhật mật khẩu thành công");
				}
				else
				{
					alert.AlertError(UserActivity.this, "Thông báo", "Cập nhật thất bại");
				}
			} catch (JSONException e) {
			}
				
			}
		});
	}
}
